#!/bin/bash
#
# Pre-commit hook to prevent committing sensitive information
#
# To install this hook:
#   cp .git-hooks-example/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#

# Colors for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Patterns to search for (case insensitive)
SENSITIVE_PATTERNS=(
    "postgres://[^:]+:[^@]+@[^/]+"  # Postgres connection strings with passwords
    "redis://[^:]+:[^@]+@"          # Redis connection strings with passwords
    "[a-zA-Z0-9_]+_API_KEY=['\"]?[a-zA-Z0-9]{20,}" # API keys
    "[a-zA-Z0-9_]+_SECRET=['\"]?[a-zA-Z0-9]{20,}"  # Secrets
    "password\s*=\s*['\"][^'\"]{8,}" # Password assignments
    "PRIVATE_KEY=['\"]?0x[a-fA-F0-9]{64}" # Ethereum private keys
)

# Files to check (staged files only)
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

if [ -z "$STAGED_FILES" ]; then
    exit 0
fi

echo "🔍 Scanning for sensitive information..."

FOUND_SENSITIVE=0

for file in $STAGED_FILES; do
    # Skip binary files
    if file "$file" | grep -q "text"; then
        for pattern in "${SENSITIVE_PATTERNS[@]}"; do
            if git diff --cached "$file" | grep -iE "$pattern" > /dev/null; then
                echo -e "${RED}❌ Potential sensitive data found in: $file${NC}"
                echo -e "${YELLOW}   Pattern: $pattern${NC}"
                FOUND_SENSITIVE=1
            fi
        done

        # Check for Supabase-like hosts
        if git diff --cached "$file" | grep -E "\.supabase\.com|\.pooler\.supabase" > /dev/null; then
            echo -e "${YELLOW}⚠️  Supabase URL found in: $file${NC}"
            echo -e "${YELLOW}   Please verify no credentials are exposed${NC}"
        fi
    fi
done

if [ $FOUND_SENSITIVE -eq 1 ]; then
    echo -e "\n${RED}================================${NC}"
    echo -e "${RED}COMMIT REJECTED${NC}"
    echo -e "${RED}================================${NC}"
    echo -e "Potential sensitive information detected in staged files."
    echo -e "Please review and remove sensitive data before committing."
    echo -e "\nTo bypass this check (not recommended):"
    echo -e "  git commit --no-verify"
    exit 1
fi

echo "✅ No sensitive information detected"
exit 0
